// NetwordThread.cpp implements code for the server thread

#include "stdafx.h"
#include "mimosav2manager.h"
#include "mimosav2managerDlg.h"
#include "Network.h"


UINT NetworkThreadFunc(LPVOID pParam)
{
	TRACE(_T("in NetworkThreadFunc\n"));

	Cmimosav2managerDlg *pParent = (Cmimosav2managerDlg *)pParam;

	BOOL bIsConnected;
	if (SUCCEEDED(IsConnected(&bIsConnected)))
	{
		pParent->PostMessage(UM_NETWORKMONITOR, (bIsConnected ? NLM_CONNECTIVITY_IPV4_INTERNET : 0), 0);
	}

	if (HANDLE hEvt = CreateEvent(NULL, FALSE, FALSE, EVT_NETWORKMONITOR))
	{
		HRESULT hr = S_OK;
		CEventSink* pEventSink1;
		CEventSink* pEventSink2;
		CEventSink* pEventSink3;

		HRESULT hrCoinit = CoInitializeEx(NULL, COINIT_MULTITHREADED);
		if (SUCCEEDED(hrCoinit) || (RPC_E_CHANGED_MODE == hrCoinit))
		{
			CComPtr<INetworkListManager> pNLM;
			hr = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL, __uuidof(INetworkListManager), (LPVOID*)&pNLM);
			if (hr == S_OK)
			{
				hr = CEventSink::StartListeningForEvents(IID_INetworkConnectionEvents, &pEventSink1, pParent->GetSafeHwnd());
				if (SUCCEEDED(hr))
				{
					hr = CEventSink::StartListeningForEvents(IID_INetworkEvents, &pEventSink2, pParent->GetSafeHwnd());
					if (SUCCEEDED(hr))
					{
						hr = CEventSink::StartListeningForEvents(IID_INetworkListManagerEvents, &pEventSink3, pParent->GetSafeHwnd());
						if (SUCCEEDED(hr))
						{
							DWORD dwRet = WaitForSingleObject(hEvt, INFINITE);
							{
								VARIANT_BOOL bIsConnected;
								HRESULT hrtemp = pNLM->get_IsConnected(&bIsConnected);
								if (SUCCEEDED(hrtemp) && VARIANT_FALSE == bIsConnected)
								{
									pParent->PostMessage(UM_NETWORKMONITOR, NLM_CONNECTIVITY_IPV4_INTERNET, 0);	// Sound Off
								}
							}

							pEventSink3->StopListeningForEvents();
							pEventSink3->Release();
						}
						pEventSink2->StopListeningForEvents();
						pEventSink2->Release();
					}
					pEventSink1->StopListeningForEvents();
					pEventSink1->Release();
				}
			}

			if (RPC_E_CHANGED_MODE != hrCoinit)
			{
				CoUninitialize();
			}
		}

		CloseHandle(hEvt);
	}

	TRACE(_T("exiting NetworkThreadFunc -----\n"));

	return 0;
}
